package dao;

import hbt.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import entidades.Rubro;
import entidades.Tarea;


public class TareaDAO {
	
	private static TareaDAO instancia = null;
	private static SessionFactory sf = null;
	
	public static TareaDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new TareaDAO();
		} 
		return instancia;
	}
	
	public void guardarTarea(Tarea fa){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(fa); 
		session.getTransaction().commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Tarea> obtenerListaTareasPorRubro(Rubro rubro) throws Exception {
		try {
			Session session = sf.openSession();
			Query q = session.createQuery("from Tarea where ID_RUBRO = "+rubro.getIdRubro());
			List<Tarea> listaTareas = new ArrayList<Tarea>(q.list());
			session.close();
			return listaTareas;
		} catch (Exception e) {
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public Tarea obtenerTareaAlAzar() throws Exception {
		try {
			Session session = sf.openSession();
			Query q = session.createQuery("from Tarea order by newid()");
			List<Tarea> listaTarea = new ArrayList<Tarea>(q.list());
			session.close();
			return listaTarea.get(0);
		} catch (Exception e) {
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public Tarea obtenerTarea(int idTarea) throws Exception {
		try {
			Session session = sf.openSession();
			Query q = session.createQuery("from Tarea where ID_TAREA = "+idTarea);
			List<Tarea> listaTarea = new ArrayList<Tarea>(q.list());
			session.close();
			return listaTarea.get(0);
		} catch (Exception e) {
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Tarea> obtenerListaTareas() throws Exception {
		try {
			Session session = sf.openSession();
			Query q = session.createQuery("from Tarea ");
			List<Tarea> listaTareas = new ArrayList<Tarea>(q.list());
			session.close();
			return listaTareas;
		} catch (Exception e) {
			throw e;
		}
	}
}
